//
//  LineCharView.swift
//  TinyShopKeeper
//
//  Created by rimi on 16/6/6.
//  Copyright © 2016年 yuying. All rights reserved.
//

import UIKit

class LineCharView: UIView {

   //选中蓝色饼状图回调_跳转操作不用返回值
    var pushToPieChartCallBack:(index:Int) -> Void
    
   //时间数组_x轴的时间数组
    var xLineTitle:[String]!
    
    //收入数组
    var yLineValue:[NSNumber]!
    
    //选中的index
    var selectIndex:Int = -1//默认没有选中
    
    //收入区域的底部间距
    var bottomY:CGFloat = 120
    //收入区域的顶部间距
    var topY:CGFloat = 40
    //收入区域的高度
    var incomeHeight:CGFloat!
    //最大收入
    var maxIncome:CGFloat!
    
    
    //前缀
    var prefixstr:String = "收入"
    
    //时段收入View 数组
    var hourIncomeViewStore:[HourIncomeView] = [HourIncomeView]()
    
    //pointview的center
    var pointStore:[CGPoint] = [CGPoint]()
    
    
    //懒加载~点了之后才会初始化的东西
    lazy  var pushToPieChartViewButton:UIButton = {
    
        let button = UIButton(type: UIButtonType.Custom)
        button.frame = CGRectMake(0,0,104,35)
        button.setBackgroundImage(imageByName("alertButtonBack.png"), forState: UIControlState.Normal)
        button.setTitle("饼状分析图", forState:.Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(19)
        button.addTarget(self, action: "pushToPieCharAction", forControlEvents: UIControlEvents.TouchUpInside)
        self.addSubview(button)
        return button
    }()
    
    
    
    //MARK:---LifeCycle
    init(frame: CGRect,callBack:(index:Int)->Void) {
        pushToPieChartCallBack = callBack
        super.init(frame: frame)
        backgroundColor = DefaultGrayColor
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    //添加背景
    func creatBackgroud(){
        let startIndex = hourIncomeViewStore.count
        let endIndex = xLineTitle.count - 1
        
        for i in startIndex...endIndex{
            let view = UIView(frame: CGRectMake(CGFloat(84*i),2,82,CGRectGetHeight(self.frame) - 4))
            view.backgroundColor = UIColor.whiteColor()
            self.addSubview(view)
        }
    }
    
    //MARK:-- 绘图 
    func StrokPath(){
        
        //1.创建时间段收入的view
        if hourIncomeViewStore.count < xLineTitle.count{
             //添加背景
            creatBackgroud()
            //创建时间段view
            creatHourIncomeViews()
        }
        
        //2.画线
        for i in 0...(pointStore.count-2){
            //取出第i个 收入的view
            let currentView = hourIncomeViewStore[i]
            let startPoint = pointStore[i]
            let endPoint = pointStore[i + 1]
            let x = CGFloat(84*i)
            let layer = shapeLayer(CGPointMake(x+startPoint.x,startPoint.y), endPoint: CGPointMake(x + CGFloat(84) + endPoint.x, endPoint.y))
            
//            self.layer.insertSublayer(layer, above: currentView.layer)
            self.layer.insertSublayer(layer, below: currentView.layer)
            
            
        }
        
        //调整收入label 的center
        for i in 0...(hourIncomeViewStore.count - 1){
            let hourIncomeView  = hourIncomeViewStore[i]
            hourIncomeView.incomeLabel.center = getIncomeLabelCenterByIndex(i)
        }

    }
    
    func getIncomeLabelCenterByIndex(index:Int) -> CGPoint{
        //默认显示在顶部
        var topSign = true
        let income1 = yLineValue[index].floatValue
        
        if index == 0{
            //第一个时间点
            let income2 = yLineValue[index + 1].floatValue
            if income2 > income1{
                topSign = false
            }
        }else if index == yLineValue.count - 1{
            //最后一个时间点
            let income0 = yLineValue[index - 1].floatValue
            if income0 > income1{
                topSign = false
            }
        }else{
            //中间的点
            let income0 = yLineValue[index-1].floatValue
            let income2 = yLineValue[index+1].floatValue
            
            if income0 > income1 && income2 > income1{
                topSign = false
            }else if income0 - income1 > income1 - income2{
                topSign = false
            }else if income2 - income1 > income1 - income0{
                topSign = false
            }
        }
        
        let pointView_center = pointStore[index]
        if topSign{
            //显示在底部
            return CGPointMake(HourIncomeView_Width/2, pointView_center.y - 40)
        }else{
            //显示在底部
            return CGPointMake(HourIncomeView_Width/2, pointView_center.y + 40)
        }
    }
    
    func getMaxIncomeValue(){
        maxIncome = 0
        for income in yLineValue{
            if maxIncome < CGFloat(income.floatValue){
            maxIncome = CGFloat(income.floatValue)
            }
        }
        
        if maxIncome == 0{
            maxIncome = 250
        }
        
    }
    
    
    //创建时间段view
    func creatHourIncomeViews(){
        let startIndex = hourIncomeViewStore.count
        let endIndex = xLineTitle.count - 1
        
        incomeHeight = CGRectGetHeight(self.frame) - self.bottomY - self.topY//收入区域的高度
        getMaxIncomeValue()//最高收入
        
        for i in startIndex...endIndex{
            
            
            let hourIncomeView = HourIncomeView(frame: CGRectMake(CGFloat(84*i), 2, 82, CGRectGetHeight(self.frame) - 4))
            
            addSubview(hourIncomeView)//加载~~~~！@！！！！！！@@！！~~！！！~
            hourIncomeViewStore.append(hourIncomeView)
           
            //添加手势
            let tapGesturer = UITapGestureRecognizer(target: self, action: "pointViewTaped:")  
            hourIncomeView.pointview.addGestureRecognizer(tapGesturer)
            
            //设置时间label的值和位置
            hourIncomeView.timeLabel.text = xLineTitle[i] + "时"
            hourIncomeView.timeLabel.center = CGPointMake(HourIncomeView_Width/2, CGRectGetHeight(hourIncomeView.frame) - 20)
            
            //pointview的位置
            //将收入 放大或者缩小 再显示，让最大收入对应高度为收入区域的高度
            //maxIncome / incomeHeight = income/height
            //100/300 = 5/height -> 15
            //height = income * incomeHeight/maxIncome
            //height = income / maxIncome * incomeHeight
            
            
            
            
            let scale = CGFloat(yLineValue[i].floatValue)/maxIncome
            let scale_Height = incomeHeight * scale
            let center_y = CGRectGetHeight(hourIncomeView.frame) - scale_Height - bottomY + topY
         
            hourIncomeView.pointview.center = CGPointMake(HourIncomeView_Width/2, center_y)
            pointStore.append(CGPointMake(HourIncomeView_Width/2, center_y))
            
            //设置收入label
            hourIncomeView.incomeLabel.text = "收入\n\(yLineValue[i])"
            hourIncomeView.incomeLabel.center = CGPointMake(HourIncomeView_Width/2, center_y + 35)
            
        }
        
        
    }
    

    //MARK:--Action
    func pushToPieCharAction(){
        //将自己隐藏，并将对应的hourIncomeView的改为非选中状态
        //和重复选中一样
        self.pushToPieChartCallBack(index:self.selectIndex)
        selectHourIncomeView(hourIncomeViewStore[selectIndex])
        
    }
    
    //
    func pointViewTaped(sender:UITapGestureRecognizer){
        
        let hourIncomeView = sender.view?.superview as! HourIncomeView
        
        //将之前选中的改成未选中的 将现在点击的改选中状态并且将饼状分析图的位置调整
        selectHourIncomeView(hourIncomeView)
        
        
    }
    
    func selectHourIncomeView(selectView:HourIncomeView){
        let currentIndex = hourIncomeViewStore.indexOf(selectView)
        if selectIndex != -1{ //之前是选中的状态
            
            
            let beforeView = hourIncomeViewStore[selectIndex]
            beforeView.pointview.pointButton.selected = false
            
            if selectIndex == currentIndex{
                //重复选中
                self.pushToPieChartViewButton.hidden = true
                selectIndex = -1
                return
            }
        }
        
        
        selectView.pointview.pointButton.selected = true
        selectIndex = currentIndex!
        let center_x = CGRectGetMidX(selectView.frame)
        let center_y = CGRectGetMinY(selectView.pointview.frame) - 25
        self.pushToPieChartViewButton.center = CGPointMake(center_x, center_y)
        self.pushToPieChartViewButton.hidden = false
    }
    
    
    
    

}
